#!/usr/bin/env bash
# 公网IP / ping / traceroute / curl测试
set -Eeuo pipefail

type log_info >/dev/null 2>&1 || { echo "[net_tools] _common.sh 未加载"; exit 1; }

show_public_ip() {
  # 依次尝试多个服务
  for url in "https://ip.gs" "https://ifconfig.me" "https://ipinfo.io/ip" "https://api.ip.sb/ip"; do
    ip=$(curl -fsSL --max-time 5 "$url" 2>/dev/null || true)
    if [[ -n "${ip}" ]]; then echo "$ip"; return 0; fi
  done
  echo "获取公网 IP 失败"
}

ping_test_interactive() {
  read -rp "输入域名/IP: " h
  [ -z "$h" ] && { echo "未输入"; return 1; }
  ping -c 4 "$h"
}

traceroute_test_interactive() {
  read -rp "输入域名/IP: " h
  [ -z "$h" ] && { echo "未输入"; return 1; }
  if command -v traceroute >/dev/null 2>&1; then
    traceroute "$h"
  else
    ensure_root
    apt_quiet_update
    DEBIAN_FRONTEND=noninteractive apt-get install -y traceroute
    traceroute "$h"
  fi
}

curl_head_test_interactive() {
  read -rp "输入 URL: " u
  [ -z "$u" ] && { echo "未输入"; return 1; }
  curl -I --max-time 10 "$u" || echo "访问失败"
}
check_ip_quality() {
  # 依赖 curl；若缺失则尝试安装
  if ! command -v curl >/dev/null 2>&1; then
    echo "缺少 curl，尝试安装..."
    if [ "$EUID" -ne 0 ]; then
      echo "请以 root 运行或先安装 curl：sudo apt-get update && sudo apt-get install -y curl"
      return 1
    fi
    apt_quiet_update
    DEBIAN_FRONTEND=noninteractive apt-get install -y curl
  fi

  echo "启动 IP 质量检测（来源：IP.Check.Place）..."
  bash <(curl -Ls IP.Check.Place)
}
